package com.idconfirmsystem.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.dom4j.DocumentException;
import org.kymjs.kjframe.http.HttpCallBack;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.idconfirmsystem.R;
import com.idconfirmsystem.activity.BagVerifyActivity;
import com.idconfirmsystem.adapter.BagVerifyQueryAdapter;
import com.idconfirmsystem.model.BagVerifyInfo;
import com.idconfirmsystem.model.BagVerifyInfoList;
import com.idconfirmsystem.model.BagVerifyInfoQuery;
import com.idconfirmsystem.model.QueryRet;
import com.idconfirmsystem.model.UserBean;
import com.idconfirmsystem.remote.ConfirmApi;
import com.idconfirmsystem.util.DateUtil;
import com.idconfirmsystem.util.XmlUtils;

public class BagVerifyListFragment extends Fragment {

	private ListView bagListView;
	ProgressBar progressbar;
	SwipeRefreshLayout swipe;
	EditText etDate;

	private List<BagVerifyInfo> bVerifyInfos;
	private BagVerifyInfoQuery query;
	private BagVerifyQueryAdapter adapter;
	QueryRet<BagVerifyInfoList> qResult;

	private DatePickerDialog datePickerDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_bag_verify_query, container, false);
		initWidget(view);
		initData();
		return view;
	}

	public void initData() {
		// TODO Auto-generated method stub
		if (query == null) {
			query = new BagVerifyInfoQuery();
		}
		if (UserBean.getInstance().getBranchNumber() != null) {
			query.setBranchNo(UserBean.getInstance().getBranchNumber());
		} else {
		}
	}

	public void initDataFromThread() {
		// TODO Auto-generated method stub
		String serviceMethod = "BankService/searchVerifyInfo";
		ConfirmApi.queryData(query, serviceMethod, callBack);
	}

	HttpCallBack callBack = new HttpCallBack() {

		@Override
		public void onFailure(int errorNo, String strMsg) {
			// TODO Auto-generated method stub
			super.onFailure(errorNo, strMsg);
		}

		@Override
		public void onSuccess(String t) {
			// TODO Auto-generated method stub
			super.onSuccess(t);
			try {
				qResult = XmlUtils.toBean(BagVerifyInfoList.class, t);
				updateList();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	};

	public void initWidget(View view) {
		bagListView = (ListView) view.findViewById(R.id.lv_bag);
		progressbar = (ProgressBar) view.findViewById(R.id.progressbar);
		swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
		etDate = (EditText) view.findViewById(R.id.et_datepicker);
		etDate.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				datePickerDialog.show();
				return false;
			}
		});
		// TODO Auto-generated method stub
		bagListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(), BagVerifyActivity.class);
				Bundle mbundle = new Bundle();
				mbundle.putSerializable("bag", bVerifyInfos.get(arg2));
				intent.putExtras(mbundle);
				startActivityForResult(intent, 1001);
			}
		});
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int date = calendar.get(Calendar.DATE);
		datePickerDialog = new DatePickerDialog(getActivity(), new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				// TODO Auto-generated method stub
				System.out.println(year+"-"+monthOfYear+"-"+dayOfMonth);
				StringBuilder t = new StringBuilder();
				t.append(year);
				t.append("-");
				if ((monthOfYear+1) < 10) {
					t.append("0");
				}
				t.append(monthOfYear+1);
				t.append("-");
				if (dayOfMonth < 10) {
					t.append("0");
				}
				t.append(dayOfMonth);
				etDate.setText(t.toString());
			}
		}, year, month, date);
	}

	public void updateList() {
		if (qResult.getTotalnum() <= 0) {
			bVerifyInfos = new ArrayList<BagVerifyInfo>();
			Toast.makeText(getActivity(), "未获取到要核验的箱包,暂使用测试数据", Toast.LENGTH_SHORT).show();
			for (int i = 0; i < 30; i++) {// testdata
				BagVerifyInfo itemBagVerifyInfo = new BagVerifyInfo();
				itemBagVerifyInfo.setArrival_time("2015090" + i);
				itemBagVerifyInfo.setBags_number("891000" + i);
				itemBagVerifyInfo.setBranch_number("XY100" + i);
				itemBagVerifyInfo.setCoordinate_title("兴业银行莲坂支行" + i);
				if (i % 2 == 1) {
					itemBagVerifyInfo.setVerifyFlag("0");
				} else {
					itemBagVerifyInfo.setVerifyFlag("1");
					itemBagVerifyInfo.setBags_seal_no(itemBagVerifyInfo.getBags_number() + "1000" + i);
					itemBagVerifyInfo.setVerifyTime(DateUtil.getCurrentDateByFormat("MM月dd日 hhmm"));
				}
				bVerifyInfos.add(itemBagVerifyInfo);
			}
		} else {
			bVerifyInfos = qResult.getResult().getBgInfos();
		}

		if (bVerifyInfos != null) {
			if (adapter == null) {
				adapter = new BagVerifyQueryAdapter(getActivity(), bagListView, bVerifyInfos);
				bagListView.setAdapter(adapter);
			} else {
				adapter.setBaglist(bVerifyInfos);
				adapter.notifyDataSetChanged();
			}
		}
	}

	BagVerifyQueryHandler myHandler = new BagVerifyQueryHandler();

	class BagVerifyQueryHandler extends Handler {
		public BagVerifyQueryHandler() {
		}

		public BagVerifyQueryHandler(Looper looper) {
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1001:// 加载数据
				updateList();
				break;

			default:
				break;
			}
		}

	}

}
